import axios from "axios";
import host from "./env.js";
import { ElMessage } from 'element-plus'

const instance = axios.create({
  baseURL: host,
  timeout: 5000,
  headers: {'X-Custom-Header': 'foobar'}
});

// 添加响应拦截器
instance.interceptors.response.use(
  function (response) {
    if (response.status === 200) {
      let data = response.data;
      if (data.code === 200) {
        return Promise.resolve(data);
      } else {
        if (data && data.data) {
          let error = "";
          for (let i in data.data) {
            error += data.data[i] + " ";
          }
          ElMessage.error(error);
        } else {
          ElMessage.error(data.message || "请求失败");
        }
      }
    }
    return response;
  },
  function (error) {
    return Promise.reject(error);
  }
);

export default {
  get(url, params) {
    return instance.get(url, { params });
  },
  post(url, data, config) {
    if (config) {
      return instance.post(url, data, config);
    }
    return instance.post(url, data);
  },
  delete(url, params) {
    return instance.delete(url, { params });
  },
  put(url, data) {
    return instance.put(url, data);
  },
  put2(url, data) {
    return instance.put(url, null, {
      params: data
    });
  }
}; 